package com.flyme.module.base.provider.listener;

import com.flyme.module.base.client.event.BalanceChangeEvent;
import com.flyme.module.base.provider.service.SysBalanceService;
import com.flyme.module.order.provider.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class BalanceChangeListener implements SmartApplicationListener {


    @Autowired
    private OrderService orderService;
    @Autowired
    private SysBalanceService balanceService;

    /**
     * 只有监听类型匹配才执行
     */
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventClass) {
        return eventClass == BalanceChangeEvent.class;
    }

    /**
     * 目标类判断
     *
     * @param aClass
     * @return
     */
    @Override
    public boolean supportsSourceType(Class<?> aClass) {
        return true;
    }

    /**
     * 余额变动处理
     */
    @Override
    @Async
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

        // 转换事件类型
        BalanceChangeEvent balanceChangeEvent = (BalanceChangeEvent) applicationEvent;
        Long userId = balanceChangeEvent.getUserId();
        BigDecimal amount = balanceChangeEvent.getAmount();
        String outTradeNo = balanceChangeEvent.getOutTradeNo();
        balanceService.chargeSuccess(userId, amount, outTradeNo);
    }

    /**
     * 同步情况下监听执行的顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
